//
//  SetupCach.m
//  Youhuiju
//
//  Created by liuovyue on 16/9/5.
//  Copyright © 2016年 yutenys. All rights reserved.
//

#import "SetupCach.h"
#define fileManager [NSFileManager defaultManager]

@implementation SetupCach


+ (NSString *)getCacheSizeWithFilePath:(NSString *)path
{
    
   

   
   
    BOOL isDirectory = NO;
    BOOL isExist = [fileManager fileExistsAtPath:path isDirectory:&isDirectory];
    if (!isExist || !isDirectory)
    {
        NSException *exception = [NSException exceptionWithName:@"fileError" reason:@"please check your filePath!" userInfo:nil];
        [exception raise];
        
    }

    
    //获取“path”文件夹下面的所有文件
    NSArray *subpathArray= [fileManager subpathsAtPath:path];
    
    NSString *filePath = nil;
    NSInteger totleSize=0;
    
    for (NSString *subpath in subpathArray)
    {
        
        filePath =[path stringByAppendingPathComponent:subpath];
        
        
        
      
        BOOL isDirectory = NO;
        
      
        BOOL isExist = [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
        
        
        if (!isExist || isDirectory || [filePath containsString:@".DS"]) continue;
 
        
        
        NSDictionary *dict=   [fileManager attributesOfItemAtPath:filePath error:nil];
        
        NSInteger size=[dict[@"NSFileSize"] integerValue];
        totleSize+=size;
    }
    
    //将文件夹大小转换为 M/KB/B
    NSString *totleStr = nil;
    
    if (totleSize > 1000 * 1000)
    {
        totleStr = [NSString stringWithFormat:@"%.1fM",totleSize / 1000.0f /1000.0f];
    }else if (totleSize > 1000)
    {
        totleStr = [NSString stringWithFormat:@"%.1fKB",totleSize / 1000.0f ];
        
    }else
    {
        totleStr = [NSString stringWithFormat:@"%.1fB",totleSize / 1.0f];
    }
    
    return totleStr;
    
    
}


+ (BOOL)clearCacheWithFilePath:(NSString *)path {
    
    NSArray *subpathArray = [fileManager contentsOfDirectoryAtPath:path error:nil];
    
    
    NSString *filePath = nil;
    NSError *error = nil;
    NSString *message = nil;
    
    for (NSString *subpath in subpathArray) {
        filePath = [path stringByAppendingPathComponent:subpath];
        [fileManager removeItemAtPath:filePath error:&error];
        
        if (error) {
        
            message = [NSString stringWithFormat:@"%@文件删除失败,请检查后重新再试",filePath];
            return NO;
            
            
        }else {
          
            message = @"成功";
            
            
        }
        
        
        
    }
    NSLog(@"message%@",message);
    
    return YES;
    
}







@end
